﻿//-----------------------------------------------------------------------
// <copyright file="ChangeTrackModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.ChangeTrack
{
    using System;
    using System.Collections.Generic;
    using App.Modules.Scene;
    using TileTool.Log;
    using TileTool.Scene;
    using TileTool.Scene.Entity;

    /// <summary>
    /// Entity change tracking editor module.
    /// </summary>
    public class ChangeTrackModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "ChangeTrackModule";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Change list we are currently adding items to.
        /// </summary>
        private int currentChangeList = 0;

        /// <summary>
        /// Pending change list. Will be locked when used.
        /// </summary>
        private IList<EntityChangedEventArgs>[] pendingChanges = new IList<EntityChangedEventArgs>[2];

        #endregion

        #region Events - Public

        /// <summary>
        /// Event triggered when we detect that entities have changed.
        /// </summary>
        public event Action<IEnumerable<EntityChangedEventArgs>> EntitiesChanged;

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            this.pendingChanges[0] = new List<EntityChangedEventArgs>();
            this.pendingChanges[1] = new List<EntityChangedEventArgs>();

            base.Startup();
        }

        /// <summary>
        /// Register for messages.
        /// </summary>
        public override void RegisterForMessages()
        {
            base.RegisterForMessages();

            SceneModule sceneModule = GetModule<SceneModule>();
            ISceneManager sceneManager = sceneModule.Scene;

            sceneManager.EntityChanged += this.ChangeTrackHandleEntityChanged;
        }

        /// <summary>
        /// Unregister for messages.
        /// </summary>
        public override void UnregisterForMessages()
        {
            base.UnregisterForMessages();

            SceneModule sceneModule = GetModule<SceneModule>();
            ISceneManager sceneManager = sceneModule.Scene;

            sceneManager.EntityChanged -= this.ChangeTrackHandleEntityChanged;
        }

        /// <summary>
        /// Work the module.
        /// </summary>
        public override void Work()
        {
            base.Work();

            IList<EntityChangedEventArgs> processList = null;

            lock (this.pendingChanges)
            {
                processList = this.pendingChanges[this.currentChangeList];
                this.currentChangeList = (this.currentChangeList + 1) & 1;
            }
                
            if (processList.Count != 0)
            {
                Action<IEnumerable<EntityChangedEventArgs>> changed = this.EntitiesChanged;

                if (changed != null)
                {
                    changed(processList);
                }

                processList.Clear();
            }
        }

        #endregion

        #region Methods - Private - Entity change tracking

        /// <summary>
        /// Handle an entity edit.
        /// </summary>
        /// <param name="args">Edit change args.</param>
        private void ChangeTrackHandleEntityChanged(EntityChangedEventArgs args)
        {
            lock (this.pendingChanges)
            {
                IList<EntityChangedEventArgs> processList = this.pendingChanges[this.currentChangeList];
                processList.Add(args);
            }
        }

        #endregion
    }
}
